<template>
  <div class="container">
    <ul class="chat_container" ref="chatContainerRef">
      <li class="chat_item" v-for="item in chatItems">
        <SenderItem v-if="item.type === ItemType.SENDER" :itemInfo="item" @notifySender="scrollToBottom"></SenderItem>
        <ThinkingItem v-else-if="item.type === ItemType.THINKING" :itemInfo="item" @notifyThinking="scrollToBottom"></ThinkingItem>
        <ErrorItem v-else-if="item.type === ItemType.ERROR" :itemInfo="item" @notifyError="scrollToBottom"></ErrorItem>
        <ReceiverItem v-else :itemInfo="item" @notifyReceiver="scrollToBottom"></ReceiverItem>

      </li>
    </ul>
    <div class="bottom_container">
      <div class="sender_container">
        <textarea class="question" placeholder="输入您的问题, 点击发送按钮或者Ctrl+Enter, 即可开启对话" 
          @input="adjustHeight" 
          ref="questionRef"
          @keydown.enter="onKeyDown"
          v-model="content"></textarea>
        <button
          :class="{ sender: sendActive, sender_disable: !sendActive }"
          @click="send" :disabled="isThinking">发送</button>
      </div>
      <div class="server_container">
        <label>
          <input type="checkbox" v-model="useTools">&nbsp;&nbsp;使用天气与地图工具
        </label>

      </div>
    </div>
  </div>
</template>

<script setup>
  import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
  import { ChatItemInfo, ItemType} from './chatItemInfo'
  import SenderItem from './components/SenderItem.vue'
  import ReceiverItem from './components/ReceiverItem.vue'
  import axios from 'axios'
  import ThinkingItem from './components/ThinkingItem.vue'
  import ErrorItem from './components/ErrorItem.vue'
  let content = ref("")
  const chatItems = reactive([])
  let useTools = ref(true)
  let isThinking = ref(false)
  let suffixDotNum = 3
  let thinkingTips = ref("正在努力思考您的问题, 请稍候...")

  let intervalTimer = null

  const questionRef = ref()
  function adjustHeight() {
    if (questionRef.value.scrollHeight < 150) {
      questionRef.value.style.height = 'auto'; // 先重置高度
      questionRef.value.style.height = `${questionRef.value.scrollHeight}px`; // 根据内容动态设置高度
    }
  }

  const chatContainerRef = ref()
  function scrollToBottom() {
    if (chatContainerRef.value.scrollHeight > chatContainerRef.value.clientHeight) {
      chatContainerRef.value.scrollTop = chatContainerRef.value.scrollHeight - chatContainerRef.value.clientHeight
    }
  }

  onMounted(() => {
    adjustHeight()
  })

  onUnmounted(()=>{
    clearInterval(intervalTimer)
  })

  let sendActive = computed(()=>{
    return !isThinking.value && content.value.trim().length > 0
  })

  function onKeyDown(event){
    if (event.ctrlKey && event.key === 'Enter') {
        send()
      }
  }

  function send() {
    let query = content.value.trim()
    if (query.trim().length === 0) {
      alert("内容为空，请先输入您的问题")
      return
    }
    const itemInfo = new ChatItemInfo(ItemType.SENDER, content.value)
    chatItems.push(itemInfo)
    content.value = ""
    isThinking.value = true
    // 传入响应式数据
    chatItems.push(new ChatItemInfo(ItemType.THINKING, thinkingTips))
    intervalTimer = setInterval(()=>{
      suffixDotNum = suffixDotNum++ % 3 + 1
      let suffixDot = ".".repeat(suffixDotNum)
      thinkingTips.value = `正在努力思考您的问题, 请稍候${suffixDot}`
    }, 500)
    let chatHost = 'http://42.194.240.231:9000'
    // let chatHost = 'http://localhost:9000'
    if(!useTools.value) {
      chatHost = 'http://42.194.240.231:9001'
      // chatHost = 'http://localhost:9001'
    }
    axios.get(`${chatHost}/chat?content=${query}`).then(res=>{
      console.log(res.data); // 处理响应数据
      chatItems.splice(chatItems.length-1, 1)
      chatItems.push(new ChatItemInfo(ItemType.RECEIVER, res.data))
      isThinking.value = false
      clearInterval(intervalTimer)
    }).catch(err=>{
      console.log(err)    // 处理响应数据
      isThinking.value = false
      clearInterval(intervalTimer)
      chatItems.splice(chatItems.length-1, 1)
      chatItems.push(new ChatItemInfo(ItemType.ERROR, "网络异常，请稍候再试"))
    })
  }


</script>

<style scoped>
  .container {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .chat_container {
    width: 60%;
    margin-top: 20px;
    max-height: calc(100vh - 200px);
    padding: 0;
    padding-right: 8px;
    overflow-y: auto;
    /* 启用垂直滚动 */
    flex-grow: 1;
    list-style: none;
  }

  /*定义滚动条宽度*/
  .chat_container::-webkit-scrollbar {
      width: 8px;
      background-color: #F5F5F5;
  }

  /*定义滚动条轨道 内阴影+圆角*/
  .chat_container::-webkit-scrollbar-track {
      box-shadow: inset 0 0 0.375rem #999;
      border-radius: 0.625rem;
      background-color: #F5F5F5;
  }

  /*定义滑块 内阴影+圆角*/
  .chat_container::-webkit-scrollbar-thumb {
      border-radius: 0.625rem;
      box-shadow: inset 0 0 0.375rem #999;
      background-color: purple;
  }

  .chat_container .chat_item {
    margin-top: 10px;
  }

  .bottom_container {
    width: 60%;
    position: fixed;
    bottom: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .bottom_container .sender_container {
    width: 100%;
    margin-top: 20px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }

  .bottom_container .server_container {
    margin-top: 10px;
    display: flex;
    flex-direction: row;
    align-self: flex-start;
  }
  .sender_container .question {
    padding: 8px;
    max-height: 960px;
    width: 90%;
    font-size: 18px;
    border-color: blueviolet;
    border-radius: 5px;
    border-style: solid;
    border-width: 2px;
    overflow-y: hidden;
    resize: none;
  }

  .sender_container .question::placeholder {
    color: gray;
  }

  .sender_container .sender {
    width: 6%;
    min-width: 60px;
    padding: 8px;
    margin-left: 5px;
    font-size: 18px;
    color: white;
    background-color: blueviolet;
    border-radius: 5px;
    border-color: blueviolet;
    border-style: solid;
    border-width: 0px;
    cursor: pointer;
  }

  .sender_container .sender:hover {
    background-color: rgba(137, 43, 226, 0.486);
    border-radius: 5px;
    border-color: rgba(137, 43, 226, 0.486);
    border-style: solid;
    border-width: 0px;
  }

  .sender_container .sender:active {
    /* 按钮稍微下移，模拟按下效果 */
    transform: translate(1px, 1px);
  }

  .sender_container .sender_disable {
    width: 6%;
    min-width: 60px;
    padding: 8px;
    margin-left: 5px;
    font-size: 18px;
    color: white;
    background-color: gray;
    border-radius: 5px;
    border-color: gray;
    border-style: solid;
    border-width: 0px;
    cursor: pointer;
  }

  @media screen and (max-width:800px){
    .chat_container {
      width: 90%;
    }
    .bottom_container {
      width: 90%;
    }
  }
</style>
